package com.dbs.donatebooksystem.controller;

import com.dbs.donatebooksystem.Service.AddressService;
import com.dbs.donatebooksystem.Service.UserService;
import com.dbs.donatebooksystem.pojo.Address;
import com.dbs.donatebooksystem.pojo.Result;
import com.dbs.donatebooksystem.pojo.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.websocket.server.PathParam;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

@RestController
@Slf4j
@CrossOrigin(origins = "http://localhost:8080", originPatterns = "http://localhost:8081")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private AddressService addressService;

    //注册用户接口
    @PostMapping("/Regist")
    public Result UserRegist(@RequestBody User user) {
        log.info("用户注册:{}", user);
        // 字段清洗（去除首尾空格）
        String account = user.getAccount() != null ? user.getAccount().trim() : "";
        String password = user.getPassword() != null ? user.getPassword().trim() : "";
        String phone = user.getPhone() != null ? user.getPhone().trim() : "";
        String nickname = user.getNickname() != null ? user.getNickname().trim() : "";
        // 基础校验
        if (account.isEmpty()) {
            return Result.error("账号不能为空");
        }
        if (password.isEmpty()) {
            return Result.error("密码不能为空");
        }
        if (nickname.isEmpty()) {
            return Result.error("昵称不能为空");
        }
        if (phone.isEmpty()) {
            return Result.error("手机号不能为空");
        }


        // 格式校验
        if (account.contains(" ")) {
            return Result.error("账号不能包含空格");
        }
        if (!Pattern.matches("^1[3-9]\\d{9}$", phone)) {
            return Result.error("手机号格式错误");
        }
        if (nickname.length() > 20) {
            return Result.error("昵称最长20个字符");
        }

        // 检查账号唯一性（使用清洗后的值）
        if (userService.selectUserByAccount(account) != null) {
            return Result.error("该用户已被注册");
        }

        // 数据清洗后重新设置值
        user.setAccount(account);
        user.setPassword(password); // 注意：实际应存储加密后的密码
        user.setPhone(phone);
        user.setNickname(nickname);

        boolean b = userService.InsertUser(user);
        return b ? Result.success("注册成功") : Result.error("注册失败");
    }

    @PostMapping("/UpdateUser")
    public Result UserUpdate(@RequestBody User user) {
        log.info("用户信息更新", user);
        userService.UpdateUser(user);
        return Result.success("更新成功");
    }

    @GetMapping("/selectAUser")
    public Result selectAUser(int id) {
        log.info("条件查询用户:{},", id);
        User user = userService.selectAUser(id);
        log.info("成功:{}", user);
        return Result.success(user);
    }

    @GetMapping("/selectUsers")
    public Result selectUsers(Integer id, String account, String nickname) {
        log.info("条件查询用户:{},{},{}", id, account, nickname);
        List<User> list = userService.selectUsers(id, account, nickname);
        log.info("成功:{}", list);
        if (list.size() == 0) {
            System.err.println("未找到用户");
        }
        return Result.success(list);
    }

    @GetMapping("/selectUserStatu")
    public Result selectUserStatu() {
        log.info("查询用户状态");
        List<Map<String, Object>> maps = userService.selectUserStatu();

        return Result.success(maps);
    }

    @DeleteMapping ("/deleteUser/{id}")
    public Result deleteUser(@PathVariable Integer id) {
        log.info("删除用户的id,{}", id);
        userService.deleteUser(id);
        return Result.success("删除成功");
    }

    @GetMapping("/address/{id}")
    public Result getAddress(@PathVariable int id) {
        log.info("获取当前用户地址:{}", id);
        List<Address> list = addressService.getAddress(id);
        return Result.success(list);
    }

    @PostMapping("address/{id}")
    public Result insertAddress(@PathVariable int id, @RequestBody Address address) {
        log.info("当前新增地址用户为:{} 新增地址信息为:{}", id, address);
        addressService.insertAddress(id, address);
        return Result.success("新增成功");
    }

    @PutMapping("/address")
    public Result updateAddress(@RequestBody Address address) {
        log.info("修改地址信息为:{}", address);
        addressService.updateAddress(address);
        return Result.success("修改成功");
    }

    @DeleteMapping("/deleteAddress")
    public Result deleteBook(@RequestParam Integer id) {
        log.info("删除地址的Id:,{}", id);
        addressService.deleteAddress(id);
        return Result.success("删除成功");
    }
}
